package copy.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import copy.com.BaseContext;
import copy.com.CustomException;
import copy.com.R;
import copy.dao.SetmealDao;
import copy.dto.SetmealDto;
import copy.pojo.Category;
import copy.pojo.Setmeal;
import copy.pojo.SetmealDish;
import copy.service.CategoryService;
import copy.service.SetmealDishService;
import copy.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.ws.Action;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author 小思
 * @Description //TODO
 * @Date $ $
 * @Param $
 * @return $
 **/

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealDao, Setmeal>implements SetmealService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;
    /**
     * 套餐分页查询 添加套餐分类name字段
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Transactional
    public Page<SetmealDto> pageAdd(int page, int pageSize, String name) {
        //动态构造key
        String key = "Setmeal_" + page + "_6";
        String s = stringRedisTemplate.opsForValue().get(key);
        if (s != null) {
            //其实使用redisTemplate 直接向下转型即可 这里处理还是较为复杂
            Page<SetmealDto> ss = JSON.parseObject(s, new TypeReference<Page<SetmealDto>>() {
            });
            return ss;
        }
        Page<Setmeal> setmealPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Setmeal> setname = new LambdaQueryWrapper<>();
        setname.like(name != null, Setmeal::getName, name);
       this.page(setmealPage, setname);
        //分页构造器中需要套餐分类表的name 所以扩展使用Dto 来传递这部分数据
        Page<SetmealDto> pageN = new Page<>();
        BeanUtils.copyProperties(setmealPage, pageN, "records");
        //单独处理 对records 集合字段做增强 拷贝在添加套餐分类字段 需要遍历该集合 且扩展数据传输对象
        List<Setmeal> records = setmealPage.getRecords();
        List<SetmealDto>list=records.stream().map((it)->{
            //拿到的每一条套参数据都带套餐分类id catrgory_id
            //扩展数据传输对象
            SetmealDto newdto = new SetmealDto();
            BeanUtils.copyProperties(it, newdto);
            //根据id拿对象
            Category category = categoryService.getById(it.getCategoryId());
            if (category != null) {
                newdto.setCategoryName(category.getName());
            }
            return newdto;
        }).collect(Collectors.toList());
        pageN.setRecords(list);
        stringRedisTemplate.opsForValue().set(key,JSON.toJSONString(pageN),15, TimeUnit.MINUTES);
        return pageN;
    }

   /*
   新增套餐 保存对应的菜品数据 添加菜品id到表setmealDish
    */
    public void saveWithSetmealDish(SetmealDto setmealDto) {
        this.save(setmealDto);
        //
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
     setmealDishes=   setmealDishes.stream().map((it) -> {
            it.setSetmealId(setmealDto.getId());
            return it;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
    }
// *删除status=o的套餐 在删除对应的菜品关系数据
// * @param

@Transactional
public void removeWithSetmealDish(List<Long> ids) {
//       in(ids) status=1 先查是否有数据
    LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(Setmeal::getStatus, 1).in(Setmeal::getId, ids);
    int count = this.count(queryWrapper);
    if (count > 0) {
        throw new CustomException("套餐正在热买，无法删除");
    }
    this.removeByIds(ids);
    //删除套餐菜品关系
    LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
    wrapper.in(SetmealDish::getSetmealId, ids);
    setmealDishService.remove(wrapper);}


    //查套餐 以及可能存在的categoryName 以及setmeal_dish数据

    public SetmealDto qWithSeDishesWithCaBySeId(Long id) {
        Setmeal setmeal = this.getById(id);
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);
      /*  //拿catrgory_id
        Long categoryId = setmeal.getCategoryId();
        Category category = categoryService.getById(categoryId);
        if (category != null) {
            setmealDto.setCategoryName(category.getName());
        }*/
        //根据套餐id 构造查询条件 查setmeal-dish表
        LambdaQueryWrapper<SetmealDish> qu = new LambdaQueryWrapper<>();
        qu.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> list = setmealDishService.list(qu);
        setmealDto.setSetmealDishes(list);

        return setmealDto;
    }

    /**
     * 更新数据 不是新增
     * @param setmealDto
     */
    public void updatetwo(SetmealDto setmealDto) {
        this.updateById(setmealDto);
        //先删除数据 在添加
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId, setmealDto.getId());
        setmealDishService.remove(wrapper);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes=   setmealDishes.stream().map((it) -> {
            it.setSetmealId(setmealDto.getId());
            return it;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
    }


}

    /**
     *
     * 删除前判断数据是否关联以及status是否为1
     * @param ids

    public void removeWithSetmealDish(List<Long> ids) {
        LambdaQueryWrapper<SetmealDish> setmeal = new LambdaQueryWrapper<>();
        setmeal.in(SetmealDish::getSetmealId, ids);
        int count = setmealDishService.count(setmeal);
        if (count > 0) {
            throw new CustomException("关联了套餐菜品关系表，套餐无法直接删除");
        }
        //能删除 还需判断数据是否status=1
        LambdaQueryWrapper<Setmeal> set = new LambdaQueryWrapper<>();
        set.eq(Setmeal::getStatus, 1).in(Setmeal::getId, ids);
        int count1 = this.count(set);
        if (count1 > 0) {
            throw new CustomException("套餐枕在热卖中，无法删除");
        }
        this.removeByIds(ids);

    }*/